<template>
    <div>
        <Drawer v-model:visible="isShowModal" :bodyStyle="{ padding: 0 }" ok-text="提交" cancel-text="取消"
            placement="right" :loading="loading" width="800px" :closable="false">
            <template #title>
                <div class="w-full flex flex-row items-center justify-between">
                    <span>详情</span>
                    <CloseOutlined @click="handleClose" />
                </div>
            </template>
            <div class="w-full min-h-full bg-[#F7F7F9]" v-if="detailResult">
                <div class="bg-white p-6 flex flex-row">
                    <img :src="'/resource/images/header.jpg'" alt="" class=" w-14 h-14 rounded-full mr-4">
                    <div class="flex flex-col flex-1">
                        <span class="text-base font-bold leading-6 text-primary">{{ detailResult.name }}</span>
                        <TreeSelect v-if="detailResult.jobTypeIds && detailResult.jobTypeIds.length"
                            v-model:value="detailResult.jobTypeIds" style="width: 100%" :bordered="false"
                            :disabled="true" :tree-data="modelOption" multiple
                            :fieldNames="{ children: 'children', label: 'name', value: 'id' }" class="list-position">
                        </TreeSelect>
                        <span v-else class="text-sm text-[#747377] leading-5 mt-0.5">--</span>
                    </div>

                    <div class="ml-12 flex flex-row items-center gap-5">
                        <span @click="handleDelTemplate()"
                            class="!py-2.5 !px-6 !rounded-lg !h-auto text-sm cursor-pointer border border-[#D7D6DD] text-[#747377]">删除</span>
                        <span class="!py-2.5 !px-6 !rounded-lg !h-auto text-sm cursor-pointer text-[#0960bd]"
                            style="background: rgba(97, 91, 246, 0.1);" @click="handleEditDetail()">编辑</span>
                    </div>
                </div>
                <div class="w-full h-full flex-1 flex" style="height: calc(100vh - 191px);">

                    <div class="flex w-full mt-4 flex-col">
                        <div class="px-6 flex flex-row items-center justify-between">
                            <span class="text-sm leading-5 text-primary">共{{ scenQuestionList?.length }}个场景问题</span>
                            <Button class="!py-2.5 !px-4 !flex flex-row items-center" type="primary"
                                @click="handleAdd()" ghost>
                                <template #icon>
                                    <PlusOutlined class="!flex" />
                                </template>场景问题</Button>
                        </div>
                        <div class="px-6 flex flex-col  overflow-hidden overflow-y-auto"
                            v-if="scenQuestionList && scenQuestionList.length">
                            <div class="pl-8" :class="index === scenQuestionList.length - 1 ? 'mb-[102px]' : ''"
                                v-for="(item, index) in scenQuestionList">
                                <div class="flex relative h-full mt-3 text-primary" :draggable="isSort"
                                    @dragenter="dragenter($event, index)" @dragover="dragover($event)"
                                    @dragstart="dragstart(index)" @dragend="dragEnd($event)">
                                    <span
                                        class="w-10 h-10 flex justify-center items-center text-white bg-[#0960bd] rounded-full text-sm font-bold absolute top-0 -left-11 z-10 border-[8px] border-[#F7F7F9]">
                                        {{ index + 1 }}
                                    </span>
                                    <Divider v-if="scenQuestionList.length > 1" type="vertical" dashed
                                        style="border-color: #615BF6; height: calc(100% - 56px) !important"
                                        class="absolute -left-6 !mx-0 w-[1px] opacity-60 !top-10" />
                                    <div class="flex flex-row mb-3 p-4 rounded-xl bg-white w-full">
                                        <div class="flex justify-start items-start mr-4 font-bold">
                                            <HolderOutlined @mouseenter="isSort = true;" @mouseleave="isSort = false"
                                                class="text-xl text-[#707275] hover:text-[#0960bd] cursor-pointer" />
                                        </div>
                                        <div class="flex flex-col flex-1 mr-[42px]" @click="handleStop">
                                            <span class="text-base font-bold leading-6">{{ item.name }}</span>
                                            <span class="mt-1.5 flex flex-row">
                                                <span class="text-[#747377] whitespace-nowrap flex">问题：</span>
                                                {{ item.question }}
                                            </span>
                                            <span class="mt-1 flex flex-row">
                                                <span class="text-[#747377] whitespace-nowrap flex">条件：</span>
                                                {{sceneExtendType.find(v => v.value == item.extendType)?.label
                                                    || '--'}}
                                            </span>
                                        </div>
                                        <div class="flex flex-row items-start gap-4">
                                            <FormOutlined @click="handleEdit(item)"
                                                class="text-lg !text-[#0960bd] cursor-pointer" />
                                            <DeleteOutlined @click="handleDel(item.id)"
                                                class="text-lg !text-[#0960bd] cursor-pointer" />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </Drawer>
        <AddQuestionModal ref="questRef" @ok="handleOkQuestion" :id="editId" />
        <Addmodal ref="addRef" @ok="handleOkDetail" :position="modelOption" />
    </div>
</template>

<script lang="ts" setup>
import { Modal, message, Button, Drawer, TreeSelect, Divider } from 'ant-design-vue'
import { JobType, KnowledgeTemplateApi, KnowledgeTemplateDetailResult, KnowledgeTemplateResult } from '@/api';
import { CloseOutlined, ExclamationCircleOutlined, PlusOutlined, FormOutlined, DeleteOutlined, HolderOutlined } from "@ant-design/icons-vue";
import Addmodal from './AddModal.vue';
import AddQuestionModal from './AddQuestionModal.vue'
import { sceneExtendType } from './index'

const emit = defineEmits(['ok']);

const isShowModal = ref(false);
const loading = ref(false);
const editId = ref<string>('');
const detailResult = ref<KnowledgeTemplateResult>();
const addRef = ref()
const modelOption = ref<JobType[]>([])

// 
const scenQuestionList = ref<KnowledgeTemplateDetailResult[]>([])
const questRef = ref();

// 编辑详情
function handleEditDetail() {
    addRef.value.handleOpen(detailResult.value)
}
function handleOkDetail() {
    emit('ok')
}
// 删除模板
async function handleDelTemplate() {
    Modal.confirm({
        title: '确认删除该模板吗?',
        icon: h(ExclamationCircleOutlined, { style: 'color:red;' }),
        async onOk() {
            try {
                await KnowledgeTemplateApi.knowledgetemplateDelete(detailResult.value!.id!.toString());
                message.success('删除成功');
                isShowModal.value = false;
                emit('ok')
            } catch (error) {
                console.log(error);
            } finally {
                loading.value = false;
            }
        },
    });
}

// 添加/编辑问题
function handleAdd() {
    questRef.value.handleOpen(undefined, detailResult.value?.id)
}

// 编辑问题
function handleEdit(data: KnowledgeTemplateDetailResult) {
    questRef.value.handleOpen(data, detailResult.value?.id)
}
function handleOkQuestion() {
    emit('ok')
}

// 删除场景问题
async function handleDel(id?: number) {
    if (id) {
        Modal.confirm({
            title: '确认删除该询问吗?',
            icon: h(ExclamationCircleOutlined, { style: 'color:red;' }),
            async onOk() {
                try {
                    await KnowledgeTemplateApi.knowledgetemplateDetaildelete(id.toString());
                    message.success('删除成功');
                    emit('ok')
                } catch (error) {
                    console.log(error);
                } finally {
                    loading.value = false;
                }
            },
        });
    }
}

function handleStop(e: any) {
    e.preventDefault();
}

// 话术排序
const isSort = ref(false)
const dragIndex = ref<number>(0);
const sortIds = ref<number[]>([]);
function dragstart(index: number) {
    dragIndex.value = index;
}
function dragenter(e: Event, index: number) {
    e.preventDefault();
    if (dragIndex.value !== index) {
        if (scenQuestionList.value.length) {
            const source = scenQuestionList.value[dragIndex.value];
            scenQuestionList.value.splice(dragIndex.value, 1);
            scenQuestionList.value.splice(index, 0, source);
            sortIds.value = scenQuestionList.value.map(v => v.id) as any[]
        }
        dragIndex.value = index;
    }
}
async function dragover(e: Event) {
    e.preventDefault();
}

async function dragEnd(e: Event) {
    e.preventDefault();
    if (detailResult.value && detailResult.value.id) {
        loading.value = true;

        try {
            await KnowledgeTemplateApi.knowledgetemplateDetailsort(sortIds.value)
            message.success('排序成功')
            emit('ok')
        } catch (error) { } finally {
            loading.value = false;
        }
    }
}


const handleOpen = (data: KnowledgeTemplateResult, sceneOptions: JobType[]) => {
    modelOption.value = sceneOptions;
    if (data) {
        detailResult.value = data;
        scenQuestionList.value = data.details || [];
        editId.value = data.id!.toString();
    }
    isShowModal.value = true;
}

function handleClose() {
    isShowModal.value = false;
}

defineExpose({ handleOpen })
</script>